from flask import current_app, render_template, session, request, jsonify

from info import sr
from info.modules.home import home_blu
from info.static.constants import CLICK_RANK_MAX_NEWS, HOME_PAGE_MAX_NEWS

from info.static.models import User, News,Category

from info.utils.response_code import RET, error_map


# 2.使用蓝图来装饰路由
@home_blu.route("/")
def index():
    # 获取状态保持的session参数
    user_id = session.get("user_id")
    # 为了使当user不存在时也不会让系统崩溃 设置user=none
    user = None
    # 从数据库中查询用户的信息
    try:
        user = User.query.get(user_id)
    except BaseException as e:
        current_app.logger.error(e)
    # 将用户信息数据转换成字典（models.py User类型中的to_dict 函数）
    user = user.to_dict() if user else None
    # 查询新闻按点击量的倒叙排列 取前10条
    # 定义一个容器来装取出来的数据
    rank_list = []
    # 从数据库中查询数据
    try:
        rank_list = News.query.order_by(News.clicks.desc()).limit(CLICK_RANK_MAX_NEWS).all()
    except BaseException as e:
        current_app.logger.error(e)
    # 将用户信息数据转换成字典（models.py News类型中的to_basic_dict 函数）
    rank_list = [news.to_basic_dict() for news in rank_list]

    # 获取分类列表
    categories = []
    # 从数据中查询数据
    try:
        categories = Category.query.all()
    except BaseException as e:
        current_app.logger.error(e)

    return render_template("news/index.html", user=user, rank_list=rank_list, categories = categories)



@home_blu.route("/favicon.ico")
def favicon():
    # 采用文件读写方式导入favicon.ico文件
    # with open("/home/python/Desktop/InfoNews16/info/static/news/favicon.ico","rb") as f:
    #     content = f.read()
    # return  content


    # send_static_file用于返回静态文件
    return current_app.send_static_file("news/favicon.ico")


@home_blu.route("/get_news_list")
def get_new_list():
    # 获取参数
    cid = request.args.get("cid")  # 新闻的类别
    cur_page = request.args.get("cur_page") # 总共的页数
    per_count = request.args.get("per_count",HOME_PAGE_MAX_NEWS) # 每页显示新闻的数量默认十条
    # 校验参数
    if not all([cid,cur_page]):
        return jsonify(errno=RET.PARAMERR,errmsg = error_map[RET.PARAMERR])
    # 将参数转换为整型
    try:
        cid = int(cid)
        cur_page = int(cur_page)
        per_count = int(per_count)
    except BaseException as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR,errmsg = error_map[RET.PARAMERR])
    news_list = []
    if cid != 1:
        news_list.append(News.category_id == cid)
    try:
        # 根据参数查询新闻内容 进行分页查询（以时间的倒叙排列）
        pn = News.query.filter(*news_list).order_by(News.create_time.desc()).paginate(cur_page,per_count)
    except BaseException as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg=error_map[RET.DBERR])
    data = {
        "news_list" : [news.to_dict() for news in pn.items],
        "total_page": pn.pages
    }
    # 以json格式返回查询结果
    return jsonify(errno=RET.OK,errmsg=error_map[RET.OK],data = data)